from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import render,redirect,HttpResponse
from web.models import UserInfo


class AuthMiddleware(MiddlewareMixin):

    def process_request(self,request):

        # 0.排除那些不需要登陆就能访问的页面
        # request.path_info    获取当前用户请求的url /login/
        if request.path_info in ['/login/','/image/code/']:
            return

        # 1.读取当前访问用户的session信息，如果能读取到，说明已经登陆，就可以继续向后走
        info_dict = request.session.get('info')
        if info_dict:
            # 用户已经登录，查找对应的 UserInfo 实例并存储在 request.user 上
            try:
                user = UserInfo.objects.get(id=info_dict['id'])
                request.user = user  # 将用户实例存储在 request 对象上
            except UserInfo.DoesNotExist:
                request.user = None  # 如果找不到用户，设置为 None
            return

        # 2.没有登陆过
        return redirect('/login/')

